package cn.org.donald.framework.util;

import cn.org.donald.framework.pojo.dto.LoginUser;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import cn.org.donald.framework.properties.AuthorizationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Json web token util
 * @author ： Donald
 * @since ： 2020/10/19 00:43
 */
@Component
public class JwtUtil {

    public static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    public static final String TOKEN_NAME = "token";

    public static final String EXPIRE_TIME_NAME = "expireTime";


    @Autowired
    private AuthorizationProperties authorizationProperties;



    @Bean
    public void setExpireTime() {
        EXPIRE_TIME = TimeUtil.getMinuteMillis(authorizationProperties.getTimeout());
    }

    private static Long EXPIRE_TIME;
    /**
     * Token sign
     */
    private static final String SIGN = "!1qaz.(";

    /**
     * Token issuer
     */
    private static final String ISSUER = "Donald";




    public static String getToken(String userId, int timeout) {
        Date date = new Date(System.currentTimeMillis() + TimeUtil.getMinuteMillis(timeout));
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(ISSUER)
                .withExpiresAt(date)
                .withClaim("userId",userId);
        return builder.sign(Algorithm.HMAC256(SIGN));
    }


    /**
     * Create a json web token by LoginUser Entity (userName and userId)
     * @param loginUser loginUser entity
     * @return result of create a json web token
     */
    public static Map<String,Object> getLoginToken(LoginUser loginUser){
        Date date = new Date(System.currentTimeMillis() + TimeUtil.getMinuteMillis(EXPIRE_TIME));
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(ISSUER)
                .withExpiresAt(date)
                .withClaim("userId",loginUser.getUserId())
                .withClaim("userName",loginUser.getUserName());
        String token = builder.sign(Algorithm.HMAC256(SIGN));
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put(TOKEN_NAME,token);
        tokenMap.put(EXPIRE_TIME_NAME,EXPIRE_TIME);
        return tokenMap;
    }

    /**
     * Decode json web token
     * @param token json web token
     * @return DecodedJWT which is result of decoding
     */
    public static DecodedJWT verify(String token){
        try {
            return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        }catch (Exception e){
            return null;
        }
    }
}

